package Core

import (
	"net/url"
	"strconv"
)

// declare HxInput object
type HxInput struct {
	FormValues url.Values
}

// Get new *HxInput from a *Request
func (r *HxRequest) Input() *HxInput {
	r.Raw.ParseForm()
	return &HxInput{r.Raw.Form}
}

// Get input data from key string
func (ipt *HxInput) Get(key string) string {
	return ipt.FormValues.Get(key)
}

// Get input int data from key string
func (ipt *HxInput) Int(key string) int {
	i, _ := strconv.ParseInt(ipt.Get(key), 10, 64)
	return int(i)
}

// Get input float data from key string
func (ipt *HxInput) Float(key string) float64 {
	f, _ := strconv.ParseFloat(ipt.Get(key), 64)
	return f
}

// Get input bool data from key string
func (ipt *HxInput) Bool(key string) bool {
	b, _ := strconv.ParseBool(ipt.Get(key))
	return b
}

// Get input data slice from key string, sometimes checkbox or select can be multi-value
func (ipt *HxInput) Slice(key string) []string {
	vs, ok := ipt.FormValues[key]
	if !ok || len(vs) == 0 {
		return []string{}
	}
	return vs
}

// Get all input data map as map[string]string, not support slice data
func (ipt *HxInput) All() map[string]string {
	m := make(map[string]string)
	for k, _ := range ipt.FormValues {
		m[k] = ipt.FormValues.Get(k)
	}
	return m
}

// Get all input data without given keys
func (ipt *HxInput) Except(v...string) map[string]string {
	all := ipt.All()
	for _, n := range v {
		delete(all, n)
	}
	return all
}

// Get mapped input data, given a new map reflection with map[new name]key
func (ipt *HxInput) Map(m map[string]string) map[string]string {
	data := make(map[string]string)
	for k, v := range m {
		data[k] = ipt.Get(v)
	}
	return data
}
